using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Timers;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Support.Design.Widget;
using Android.Support.V4.App;
using Android.Support.V4.View;
using Android.Support.V4.Widget;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Text;
using Android.Text.Style;
using Android.Util;
using Android.Views;
using Android.Widget;
using Com.Gcssloop.Widget;
using mb;
using mb.Droid;

namespace libmp
{
    public class SignInView
    {
        static EditText telphoneEdit;
        static EditText passwordEdit;
        static TextView telphoneTextView;
        static TextView passwordTextView;
        static TextView msgTextView;
        static ILog logger = ServiceLocator.Instance.Get<ILog>();
        static API.IStartOption startOption = App.StartOption;

        static MyRecyclerAdapter adapter;

        static Action<bool> OnFinish;
        static MyFragment fragment;

        public static MyFragment FragmentFrom(Type ownerClass)
        {
            var mi = ownerClass.GetMethod("CreateFragment");
            return mi.Invoke(null, null) as MyFragment;
        }
        public static MyFragment CreateFragment(Action<bool> OnFinish)
        {
            SignInView.OnFinish = OnFinish;
            fragment = new MyFragment()
            {
                MyOnCreateView = (f, container) => CreateView(f),
                MyOnResume = (f) => OnResume(),
            };
            return fragment;

        }

        static void OnResume()
        {
            logger.Log("SignInView resume");

            // Util.PopMgr.ShowMsgbox("会员到期日：");
            // Util.PopMgr.ShowConfirm("选择一下吧：\n吃什么呢？", (b) => { logger.Log("select", b); });
        }

        public static View CreateView(MyFragment f)
        {
            var ctx = StartActivity.This;
            LinearLayout FLayout = new LinearLayout(ctx);
            FLayout.Orientation = Orientation.Vertical;
            FLayout.SetBackgroundColor(Color.Rgb(238, 238, 238));

            LinearLayout signinLayoutTop = new LinearLayout(ctx);
            signinLayoutTop.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 120);
            signinLayoutTop.SetGravity(GravityFlags.Center);
            signinLayoutTop.SetBackgroundColor(Color.Rgb(251, 114, 153));

            LinearLayout signinLayoutLeft = new LinearLayout(ctx);
            var signinLayoutLeftParams = new LinearLayout.LayoutParams(180, LinearLayout.LayoutParams.MatchParent);
            signinLayoutLeft.LayoutParameters = signinLayoutLeftParams;
            signinLayoutLeft.SetVerticalGravity(GravityFlags.CenterVertical);
            var returnImageView = new ImageView(ctx);
            returnImageView.SetImageDrawable(Util.DrawableFromFile("user/Fanhui.png"));
            var returnImageViewParams = new LinearLayout.LayoutParams(40, 40);
            returnImageViewParams.LeftMargin = 10;
            returnImageViewParams.RightMargin = 30;
            returnImageView.LayoutParameters = returnImageViewParams;
            signinLayoutLeft.AddView(returnImageView);

            var returnText = new TextView(ctx);
            returnText.Text = "返回";
            returnText.SetTextColor(Color.White);
            returnText.SetTypeface(Typeface.Default, TypefaceStyle.Bold);
            returnText.SetTextSize(ComplexUnitType.Pt, 7);
            signinLayoutLeft.AddView(returnText);
            signinLayoutTop.AddView(signinLayoutLeft);
            signinLayoutLeft.Click += (s, e) =>
            {
                logger.Log("返回------------");
                f.FragmentManager.PopBackStack();
                OnFinish(false);
            };

            LinearLayout signinLayoutCentar = new LinearLayout(ctx);
            signinLayoutCentar.LayoutParameters = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1);
            signinLayoutCentar.SetGravity(GravityFlags.Center);
            var signinTopText = new TextView(ctx);
            signinTopText.Text = "登录";
            signinTopText.SetTextColor(Color.White);
            signinTopText.SetTypeface(Typeface.Default, TypefaceStyle.Bold);
            signinTopText.SetTextSize(ComplexUnitType.Pt, 9);
            signinLayoutCentar.AddView(signinTopText);
            signinLayoutTop.AddView(signinLayoutCentar);

            LinearLayout signinLayoutRight = new LinearLayout(ctx);
            signinLayoutRight.LayoutParameters = new LinearLayout.LayoutParams(190, LinearLayout.LayoutParams.MatchParent);
            signinLayoutRight.SetGravity(GravityFlags.Center);
            var ForgetPassText = new TextView(ctx);
            // ForgetPassText.Text = "忘记密码";
            ForgetPassText.SetTextColor(Color.White);
            ForgetPassText.SetTypeface(Typeface.Default, TypefaceStyle.Bold);
            ForgetPassText.SetTextSize(ComplexUnitType.Pt, 7);
            signinLayoutRight.AddView(ForgetPassText);
            signinLayoutTop.AddView(signinLayoutRight);
            FLayout.AddView(signinLayoutTop);

            LinearLayout msgTextViewLayout = new LinearLayout(FLayout.Context);
            var msgTextViewLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 70);
            msgTextViewLayoutParams.TopMargin = 230;
            msgTextViewLayout.LayoutParameters = msgTextViewLayoutParams;
            // msgTextViewLayout.SetBackgroundColor(Color.Red);
            msgTextViewLayout.SetGravity(GravityFlags.Center);
            FLayout.AddView(msgTextViewLayout);
            msgTextView = new TextView(FLayout.Context);
            msgTextView.SetTextColor(Color.Rgb(251, 114, 153));
            msgTextView.SetTextSize(ComplexUnitType.Pt, 7);
            msgTextViewLayout.AddView(msgTextView);

            LinearLayout signinLayoutBottom = new LinearLayout(ctx);
            var LayoutParametersParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 240);
            // LayoutParametersParams.TopMargin = 300;
            signinLayoutBottom.LayoutParameters = LayoutParametersParams;
            signinLayoutBottom.SetBackgroundColor(Color.White);
            signinLayoutBottom.Orientation = Orientation.Vertical;

            telphoneEdit = new EditText(ctx);
            telphoneTextView = new TextView(ctx);
            CreateEditText(signinLayoutBottom, telphoneEdit, telphoneTextView, "在这里输入手机号或邮箱", false, 0);

            passwordEdit = new EditText(ctx);
            passwordTextView = new TextView(ctx);
            CreateEditText(signinLayoutBottom, passwordEdit, passwordTextView, "请输入密码", true, 1);

            FLayout.AddView(signinLayoutBottom);

            LinearLayout loginRegisterLayout = new LinearLayout(ctx);
            var loginRegisterLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 110);
            loginRegisterLayoutParams.TopMargin = 30;
            loginRegisterLayout.LayoutParameters = loginRegisterLayoutParams;
            loginRegisterLayout.Orientation = Orientation.Horizontal;
            loginRegisterLayout.SetGravity(GravityFlags.Center);
            LoginRegisterButton(f, loginRegisterLayout);
            FLayout.AddView(loginRegisterLayout);

            if (startOption.GetBoolValue("autoFillRegInfo"))
            {
                telphoneEdit.Text = "13512341234";
                passwordEdit.Text = "111111";
            }

            return FLayout;
        }

        static void CreateEditText(ViewGroup root, EditText editText, TextView textView, string editTextHint, bool ifPass, int i)
        {

            var IconArray = new string[]
            {
                "user/Land_character.png",
                "user/Land_Password.png",
            };

            var ctx = StartActivity.This;

            LinearLayout telphoneLayout = new LinearLayout(ctx);
            var telphoneLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 120);
            telphoneLayout.LayoutParameters = telphoneLayoutParams;
            telphoneLayout.SetVerticalGravity(GravityFlags.CenterVertical);

            var telphoneImageView = new ImageView(ctx);
            telphoneImageView.SetImageDrawable(Util.DrawableFromFile(IconArray[i]));
            var telphoneImageViewParams = new LinearLayout.LayoutParams(40, 40);
            telphoneImageViewParams.LeftMargin = 40;
            telphoneImageView.LayoutParameters = telphoneImageViewParams;
            telphoneLayout.AddView(telphoneImageView);
            var editTextParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 120);
            editTextParams.LeftMargin = -15;
            editTextParams.RightMargin = 45;
            editText.LayoutParameters = editTextParams;
            editText.SetBackgroundColor(Color.Rgb(204, 204, 204));
            editText.SetPadding(50, 2, 0, 0);
            editText.Background = null;
            editText.SetTextColor(Color.Rgb(30, 30, 30));
            editText.SetHintTextColor(Color.Rgb(204, 204, 204));
            editText.SetTextSize(ComplexUnitType.Pt, 7);
            editText.Hint = editTextHint;
            editText.Focusable = true;
            editText.SetSingleLine();
            if (ifPass)
            {
                editText.InputType = InputTypes.TextVariationPassword | InputTypes.ClassText;
            }
            telphoneLayout.AddView(editText);

            var pix = new LinearLayout(ctx);
            var pixParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 1);
            pix.LayoutParameters = pixParams;
            pix.SetBackgroundColor(Color.Rgb(204, 204, 204));
            root.AddView(pix);
            root.AddView(telphoneLayout);
        }

        static void LoginRegisterButton(MyFragment f, LinearLayout loginRegisterLayout)
        {
            var ctx = StartActivity.This;

            var layoutRegister = new LinearLayout(ctx);
            layoutRegister.SetGravity(GravityFlags.Center);
            var layoutRegisterParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1);
            layoutRegister.LayoutParameters = layoutRegisterParams;
            //圆角
            RCRelativeLayout registerRCLayout = new RCRelativeLayout(ctx);
            registerRCLayout.SetVerticalGravity(GravityFlags.CenterVertical);
            var registerRCLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent);
            registerRCLayoutParams.LeftMargin = 40;
            registerRCLayoutParams.RightMargin = 20;

            registerRCLayout.LayoutParameters = registerRCLayoutParams;
            registerRCLayout.SetRadius(20);

            LinearLayout btnRegister = new LinearLayout(ctx);
            var btnRegisterParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent);
            btnRegister.LayoutParameters = btnRegisterParams;
            btnRegister.SetBackgroundColor(Color.White);
            btnRegister.SetGravity(GravityFlags.Center);
            registerRCLayout.AddView(btnRegister);

            var RegisterTextView = new TextView(ctx);
            RegisterTextView.Text = "注册";
            RegisterTextView.SetTypeface(Typeface.Default, TypefaceStyle.Bold);
            RegisterTextView.SetTextSize(ComplexUnitType.Pt, 9);
            btnRegister.AddView(RegisterTextView);
            layoutRegister.AddView(registerRCLayout);
            loginRegisterLayout.AddView(layoutRegister);

            btnRegister.Click += (s, e) =>
            {
                logger.Log("注册了1");
                MeView.Register();
            };
            //登录
            var layoutLogin = new LinearLayout(ctx);
            layoutLogin.SetGravity(GravityFlags.Center);
            var layoutLoginParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1);
            layoutLogin.LayoutParameters = layoutLoginParams;
            //圆角
            RCRelativeLayout loginRCLayout = new RCRelativeLayout(ctx);
            loginRCLayout.SetVerticalGravity(GravityFlags.CenterVertical);
            var loginRCLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent);
            loginRCLayoutParams.RightMargin = 40;
            loginRCLayoutParams.LeftMargin = 20;
            loginRCLayout.LayoutParameters = loginRCLayoutParams;
            loginRCLayout.SetRadius(20);
            //登录底部
            LinearLayout btnLogin = new LinearLayout(ctx);
            var btnLoginParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent);
            btnLogin.LayoutParameters = btnLoginParams;
            btnLogin.SetBackgroundColor(Color.Rgb(251, 114, 153));
            btnLogin.SetGravity(GravityFlags.Center);
            loginRCLayout.AddView(btnLogin);

            var loginTextView = new TextView(ctx);
            loginTextView.Text = "登录";
            loginTextView.SetTextColor(Color.White);
            loginTextView.SetTypeface(Typeface.Default, TypefaceStyle.Bold);
            loginTextView.SetTextSize(ComplexUnitType.Pt, 9);
            btnLogin.AddView(loginTextView);

            layoutLogin.AddView(loginRCLayout);
            loginRegisterLayout.AddView(layoutLogin);
            btnLogin.Click += (s, e) =>
            {
                // logger.Log("登录了------", telphoneEdit.Text);
                bool promptError = true;
                initWrongMsg();
                string telphoneString = telphoneEdit.Text;
                string passwordString = passwordEdit.Text;
                if (verifyTelephone() == false)
                {
                    promptError = false;
                }
                else if (passwordString.Length < 6)
                {
                    msgTextView.Text = "密码不能少于6位";

                    promptError = false;
                }
                else if (passwordString.Length > 15)
                {
                    msgTextView.Text = "密码不能大于15位";
                    promptError = false;
                }
                if (promptError)
                {
                    logger.Log("验证通过，执行登录操作····");

                    UserLogin(telphoneString, passwordString);

                }
            };
        }

        static bool verifyTelephone()
        {
            // var MyTool = new MyTool();
            string telphoneString = telphoneEdit.Text;
            if (telphoneString.Length == 0)
            {
                msgTextView.Text = "请填写手机号码";
                return false;
            }
            else if (!Util.IsPhoneNo(telphoneString))
            {
                msgTextView.Text = "手机号码类型错误";
                return false;
            }
            return true;
        }

        static void initWrongMsg()
        {
            msgTextView.Text = "";
        }

        static string baseUrl = App.CurrentServerUrl;
        static async void UserLogin(string telephone, string password)
        {
            password = Util.MD5Encrypt32(password);

            var waiter = Util.PopMgr.ShowWait("登录中", 5);
            var res = await User.me.Login(telephone, password);
            waiter.Close();
            if (res != null)
            {
                // msgTextView.Text = res;
                Util.PopMgr.ShowMsgbox($"登录失败\n{res}");
                return;
            }

            fragment.FragmentManager.PopBackStack();
            OnFinish(true);

            Util.PopMgr.ShowToast("登录成功");
        }

    }

}